<template>
  <div class="e-map" ref="eMap">
    <el-button v-if="isFullscreen" :icon="ZoomOut" class="absolute z-10 right-5 top-5" @click="toggleScreen"></el-button>
    <el-button v-else :icon="ZoomIn" class="absolute z-10 right-5 top-5" @click="toggleScreen"></el-button>
    <EChartsComponent ref="mapChart" :option="chartOption" @map-click="handleClick"> </EChartsComponent>
    <el-menu class="z-100" v-if="menuVisible" :style="menuStyle">
      <el-menu-item v-if="selectDevice?.status === 1" @click="handleMenu(1)">安装</el-menu-item>
      <el-menu-item v-if="selectDevice?.status === 0" @click="handleMenu(2)">拆除</el-menu-item>
      <el-menu-item @click="handleMenu(-1)">取消</el-menu-item>
    </el-menu>
    <el-dialog v-model="showDeadline" title="下发任务" width="500">
      <el-form :model="taskForm">
        <el-form-item label="任务类型" :label-width="80">
          <el-tag v-if="taskForm.taskType === 1">安装</el-tag>
          <el-tag v-else>拆除</el-tag>
        </el-form-item>
        <el-form-item label="铁鞋编号" :label-width="80">
          <el-input readonly v-model="taskForm.deviceId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="截止时间" :label-width="80">
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="taskForm.deadLine"
            format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="Select date and time"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDimissTask">取消</el-button>
          <el-button type="primary" @click="handleConfirTask"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { DeviceInfo } from '@/api/zntx-app/device/types';
import {
    ZoomIn,
    ZoomOut,
} from '@element-plus/icons-vue'
import screenfull from "screenfull";
import { ref } from 'vue';
import {addTask} from "@/api/zntx-app/task";
import {TaskForm} from "@/api/zntx-app/task/types";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps<{
    deviceInfo: DeviceInfo[]
}>();
const taskForm = ref({
  deviceId: '',
  taskType: 1,
  deadLine: null
});
const selectedDevice = ref(null);
const showDeadline = ref(false);
const mapChart = ref(null);
const menuVisible = ref(false);
const menuStyle = ref({ top: '0px', left: '0px' });
const isFullscreen = ref(false);
const eMap = ref(null);
const selectDevice = ref(null);
const series: null | any = ref(null);
const customRender = (params, api, status) => {
    let level = api.value[2];
    let color = level > 0.7 ? '#0F0' : (level > 0.4 ? '#FF0' : '#F00');
    let coord = api.coord([api.value(0), api.value(1)]);
    let circleColor = status === 0? '#0F0':(status === 1?'#FF0':'#F00')
    console.log(coord)
    return {
        type: 'group',
        children: [
            {
                type: 'circle',
                shape: {
                    cx: coord[0],
                    cy: coord[1],
                    r: 12
                },
                style: {
                    fill: color,
                    stroke: '#fff', // 电量环颜色
                    lineWidth: 0.5
                }
            },
            {
                type: 'ring',
                shape: {
                    cx: coord[0],
                    cy: coord[1],
                    r: 10, // 电量大小控制半径
                },
                style: {
                    fill: circleColor,
                    stroke: '#fff', // 电量环颜色
                    lineWidth: 0.5
                }
            }
        ]

    }
}
watch(() => props.deviceInfo, (newValue) => {
    if (newValue.length === 0) return
    console.log("watch", newValue.length)
    series.value = [{
        name: '工作',
        type: 'scatter',
        coordinateSystem: 'geo', // 指定使用地理坐标系
        data: newValue.filter(x => x.status === 0).map(x => {
            console.log('x', x)
            return {
                name: x.deviceId,
                status: 0,
                value: [x.location.x-300, x.location.y-128, 5]
            }
        }),
        // 可以设置散点的样式
        symbolSize: function (val: number[]) {
            return val[2] * 4; // 根据数据的第三个值设置散点的大小
        },
        itemStyle: {
            color: "#0F0"
        },
        renderItem: function (params, api) {
           customRender(params, api, 0)
        }
    },
    {
        name: '空闲',
        type: 'scatter',
        coordinateSystem: 'geo', // 指定使用地理坐标系
        data: newValue.filter(x => x.status === 1).map(x => {
            return {
                name: x.deviceId,
                status: 1,
                value: [x.location.x - 300, x.location.y - 128, 5]
            }
        }),
        // 可以设置散点的样式
        symbolSize: function (val: number[]) {
            return val[2] * 4; // 根据数据的第三个值设置散点的大小
        },
        itemStyle: {
            color: "#FF0"
        },
        renderItem: function (params, api) {
           customRender(params, api, 1)
        }
    },
    {
        name: '报警',
        type: 'scatter',
        coordinateSystem: 'geo', // 指定使用地理坐标系
        data: newValue.filter(x => x.status === 2).map(x => {
            return {
                name: x.deviceId,
                status: 2,
                value: [x.location.x-300, x.location.y-128, 5]
            }
        }),
        // 可以设置散点的样式
        symbolSize: function (val: number[]) {
            return val[2] * 4; // 根据数据的第三个值设置散点的大小
        },
        itemStyle: {
            color: "#F00"
        },
        renderItem: function (params, api) {
            customRender(params, api, 2)
        }
    }];
    console.log('series', series)
    console.log('options', chartOption)
    // mapChart.value.initChart()
})

const chartOption = ref({
    title: {
        text: '重庆机务段整备库地图',
        left: 'center',
        top: '5%',
        textStyle: {
          fontSize: 30
        }
    },
    legend: {
        show: true,
        top: '10%',
        right: '5%'
    },
    geo: {
        map: 'track-map',
        roam: false,
        layoutSize: '130%',
        layoutCenter: ['50%', '50%'],
        emphasis: {
            itemStyle: {
                color: undefined
            },
            label: {
                show: true
            }
        },
    },
    tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
            var data = params.data || [0, 0, 0];
            return data.name + '：<br>经度: ' + data.value[0] + '<br>纬度: ' + data.value[1] + '<br>状态: ' + data.status;
        }
    },
    series: series,
    graphic:[
      {
        type: 'group',
        left: '10%', // 指定位置，可以根据需要调整
        top: '10%',
        children: [
          {
            type: 'image',
            style: {
              image: 'arrow.png',  // 填充颜色，可以自定义
              width: 40,
              height: 40,
            },
            rotation: -Math.PI / 2
          },
          {
            type: 'text',
            left: 20,
            top: 10,
            style: {
              text: '北',  // 指北
              fill: 'white',
              font: 'bold 20px sans-serif'
            }
          }
        ]
      }
    ]
});

const toggleScreen = () => {
    if (screenfull.isEnabled && eMap.value) {
        screenfull.toggle(eMap.value).then(() => {
            isFullscreen.value = screenfull.isFullscreen;
        });
    }
}

const handleClick = (params: any) => {
    console.log('hello',params);
    if (params) {

        selectDevice.value = params.data;
        menuStyle.value = {
            top: `${params.event.offsetY}px`,
            left: `${params.event.offsetX}px`
        };
        console.log('hello-world',menuStyle.value)
        menuVisible.value = true;
    }
}
const handleMenu = (params:number) => {
    // console.log("device", selectDevice)
    if(params === -1){
      menuVisible.value = false;
      return;
    }
    menuVisible.value = false;
    taskForm.value.deviceId = selectDevice.value.name;
    taskForm.value.taskType = params
    showDeadline.value = true;
}

// 监听全屏状态的变化
if (screenfull.isEnabled) {
    screenfull.on('change', () => {
        isFullscreen.value = screenfull.isFullscreen;
    });
}

const init = () => {
    if (mapChart.value) {
        mapChart.value.initChart()
    }
}
const handleDimissTask = () =>{
  showDeadline.value = false;
}

const handleConfirTask = () => {
  const data: TaskForm = {
    deviceId: taskForm.value.deviceId,
    taskType: taskForm.value.taskType-1,
    deadLine: taskForm.value.deadLine
  }
  addTask(data).then(res => {
    if(res.code === 200){
      proxy?.$modal.msgSuccess("任务下发成功");
      handleDimissTask();
    }else{
      proxy?.$modal.msgError("任务下发失败");
      handleDimissTask();
    }
  });
}
onMounted(() => {
    //console.log("props", props)
})
defineExpose({
    init
});
</script>
<style scoped>
.e-map {
    height: calc(100vh - 84px);
    width: 100%;
}

.el-menu {
    position: absolute;
}
</style>
